// 引入画布
const { createCanvas } = require('canvas');
// 引入Token生成包
const jwt = require('jsonwebtoken');
const secrKey = 'dadongdong';

/**
 * 生成token
 * @param data 需要生成token的数据{username: 'admin', password: '123456'}
 * @return {string} 返回生成的token 
 * */
function generateToken(data) {
    return jwt.sign(data, secrKey, { expiresIn: '1h' });
}


/**
 * 验证token
 * @param token 需要要验证的token
 * @return {JSON} 返回token中的数据 {username: 'admin', password: '123456'}
 */
function verifyToken(token) {
     // 截取token
     const tokenArr = token.split("Bearer ")[1];
    try {
        return jwt.verify(tokenArr, secrKey);
    } catch (err) {
        return false;
    }
     
}

/**
 * 验证码配置信息
 * @returns {{text: string, base64String: string}}
 */
function generateCaptcha() {
    const canvas = createCanvas(150, 50);
    const ctx = canvas.getContext('2d');
   
    // 背景颜色
    ctx.fillStyle = '#f4f4f4';
    ctx.fillRect(0, 0, 150, 50);
   
    // 文本属性
    ctx.fillStyle = '#000';
    ctx.font = '28px sans-serif';
    ctx.textBaseline = 'middle';
    ctx.textAlign = 'center';
   
    // 生成随机数字
    const text = ('' + Math.random()).substring(2, 8);
   
    // 绘制文本
    ctx.fillText(text, 75, 25);
   
    // 转换为base64
    const buffer = canvas.toBuffer('image/png');
    const base64String = buffer.toString('base64');
   
    return { text, base64String };
  }

/**
 * 获取请求ip地址
 * @param req 请求对象
 * @return {string} 客户端ip地址
 */
function getClientIp(req) {
    let ClientIp = req.connection.remoteAddress || req.socket.remoteAddress || (req.connection.socket ? req.connection.socket.remoteAddress : null) || req.headers['x-forwarded-for']; // x-forwarded-for容易被伪造
    if (ClientIp.indexOf('::ffff:') !== -1) {
        ClientIp = ClientIp.substring(7);
    }
    return ClientIp
}

/**
 * json的key值下划线开头转大写
 * @param obj json对象
 * @returns {any} 转换后的json对象
 */
function toCamelCase(obj) {
    const camelCaseObj = {};
    for (const key in obj) {
        if (obj.hasOwnProperty(key)) {
            const camelCaseKey = key.replace(/_(\w)/g, (match, p1) => p1.toUpperCase());
            camelCaseObj[camelCaseKey] = obj[key];
        }
    }
    return camelCaseObj;
}

/**
 * json的key大写转下划线开头
 * @param obj json对象
 * @returns {any} 转换后的json对象
 * */
function toUnderlineCase(obj) {
    const underlineCaseObj = {};
    for (const key in obj) {
        if (obj.hasOwnProperty(key)) {
            const underlineCaseKey = key.replace(/([A-Z])/g, (match, p1) => `_${p1.toLowerCase()}`);
            underlineCaseObj[underlineCaseKey] = obj[key];
        }
    }
    return underlineCaseObj;
}

/**
 * 首字母大写
 * @param str 字符串
 * @returns {string} 首字母大写的字符串
 * */
function capitalizeFirstLetter(str) {
    return str.charAt(0).toUpperCase() + str.slice(1);
}

/**
 * 递归生成树
 * @param pid 父id
 * @param arr 数据
 * @returns {any[]} 树形结构数据
 * */
function recursionGenerateTree(pid, arr) {
    let array = []
    arr.forEach(item => {
        if (item.pid == pid) {
            delete item.pid
            // 判断是否有子节点
           let children = recursionGenerateTree(item.id, arr)
            if (children.length > 0) {
                item.children = children // 接收子节点
            }
            array.push(item)
        };
    })
    return array // 返回查找到的节点
}

/**
 * 补零
 * @param num 数字
 * @param length 补零位数
 * @returns {string} 补零后的字符串
 * */
function addZero(num,num_leng){
    num = num.toString()
    num_leng = parseInt(num_leng);
    if(num_leng - num.length == 1){
        num = "0" + num;
        return num;
    }
    if(num_leng - num.length == 2){
        num = "00" + num;
        return num;
    }
    if(num_leng - num.length == 3){
        num = "000" + num;
        return num;
    }
    if(num_leng - num.length == 4){
        num = "0000" + num;
        return num;
    }
    if(num_leng - num.length == 5){
        num = "00000" + num;
        return num;
    }
    if(num_leng - num.length == 6){
        num = "000000" + num;
    }
    if(num_leng - num.length <= 0){
        return num;
    }
}
// 暴露 
module.exports = {
    capOptions:generateCaptcha, // 验证码配置信息
    generateToken, // 生成token
    verifyToken, // 验证token
    getClientIp, // 获取客户端ip
    toCamelCase, // json的key值下划线开头转大写
    capitalizeFirstLetter,  // 首字母大写
    toUnderlineCase, // json的key大写转下划线开头
    recursionGenerateTree, // 递归生成树
    addZero, // 补零
};